package com.lavegue.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.time.DateUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.lavegue.common.BaseHibernateDao;
import com.lavegue.common.Page;
import com.lavegue.dao.ManageMsgDao;
import com.lavegue.model.ManageMsg;
import com.lavegue.model.Msg;
import com.lavegue.model.UserInfo;
import com.lavegue.util.DateTimeUtil;
import com.lavegue.util.StringUtil;

/**
 * author: luoweibin
 * date:2011-12-29
 * description:
 *
 */
public class ManageMsgDaoImpl extends BaseHibernateDao<ManageMsg, Integer> implements ManageMsgDao {

	public ManageMsgDaoImpl() {
		super(ManageMsg.class);
	}

	public Page<ManageMsg> findPage(int maybeSend, Date startTime, Date endTime,
			String title, int type, int group, int pageNo, int pageSize) {
		List<Criterion> conditions = new ArrayList<Criterion>();
//		if (startTime != null && endTime != null) {
//			Date start = DateTimeUtil.getDateStart(startTime);
//			Date end = DateTimeUtil.getDateStart(DateUtils.addDays(endTime, 1));
//			conditions.add(Restrictions.between("addTime",start, end));
//		} else if (startTime != null && endTime == null) {//结束时间为空，把开始作为结束
//			Date start = DateTimeUtil.getDateStart(startTime);
//			Date end = DateTimeUtil.getDateStart(DateUtils.addDays(startTime, 1));
//			conditions.add(Restrictions.between("addTime",start, end));
//			System.out.println(DateTimeUtil.formatLong(start));
//			System.out.println(DateTimeUtil.formatLong(end));
//		} else if (startTime == null && endTime != null) {//开始时间为空，把结束时间作为开始
//			Date start = DateTimeUtil.getDateStart(endTime);
//			Date end = DateTimeUtil.getDateStart(DateUtils.addDays(endTime, 1));
//			System.out.println(DateTimeUtil.formatLong(start));
//			System.out.println(DateTimeUtil.formatLong(end));
//			conditions.add(Restrictions.between("addTime",start, end));
//		}
		
		if (startTime != null) {
			conditions.add(Restrictions.ge("addTime", DateTimeUtil.getDateStart(startTime)));
		}
		
		if (endTime != null) {
			conditions.add(Restrictions.lt("addTime", DateTimeUtil.getDateStart(DateUtils.addDays(endTime, 1))));
		}
		
		if (maybeSend != -1) {
			conditions.add(Restrictions.eq("maybeSend", maybeSend));
		}
		
		if (!StringUtil.isEmpty(title)) {
			conditions.add(Restrictions.like("title", title, MatchMode.ANYWHERE));
		}
		if(type != 0) {
			conditions.add(Restrictions.eq("bisType.id", type));
		}
		if (group != 0) {
			conditions.add(Restrictions.eq("bisGroup.id", group));
		}
		return this.findPage(pageNo, pageSize, conditions, Order.desc("addTime"));
	}

	public Page<ManageMsg> findPageByTypeAndGroup(int type, int group,
			final int pageNo, final int pageSize, UserInfo user, final String title) {
		StringBuffer sb = new StringBuffer("from ManageMsg where 1=1 ");
		if (type > 0) {
			//conditions.add(Restrictions.eq("bisType.id", type));
			sb.append(" and bisType.id=" + type);
		}
		if (group > 0) {
			//conditions.add(Restrictions.eq("bisGroup.id", group));
			sb.append(" and bisGroup.id=" + group);
		}
		if (!StringUtil.isEmpty(title)) {
			sb.append("and title like ?");
		}
		if (user != null && (user.getType() == 1)) {//1是vip
//			Criterion c1 = Restrictions.isNull("bisGroup.company.id");
//			SimpleExpression c2 = Restrictions.eq("bisGroup.company.id", user.getCompany().getId());
//			LogicalExpression or = Restrictions.or(c1, c2);
			sb.append(" and (bisGroup.company.id is null or bisGroup.company.id=" + user.getCompany().getId() + ")");
		}
		
		sb.append(" order by addTime desc");
		final String hql = sb.toString();
		return (Page<ManageMsg>) this.getHibernateTemplate().execute(new HibernateCallback() {
			
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {
				Query query = session.createQuery("select count(*) " + hql);
				Query query2 = session.createQuery(hql);
				if (!StringUtil.isEmpty(title)) {
					query.setString(0, "%" +title.trim() + "%");
					query2.setString(0, "%" +title.trim() + "%");
				}
				int total = Integer.valueOf(query.uniqueResult().toString());
				int totalPage = countPage(total, pageSize);
				if (pageNo > total) {
					query2.setFirstResult(computeStart(totalPage, pageSize));
				} else {
					query2.setFirstResult(computeStart(pageNo, pageSize));
				}
				query2.setMaxResults(pageSize);
				List list = query2.list();
			////如果页数大于总页数，则取最后一页
				int pageNoNew = (pageNo > totalPage)?  totalPage: pageNo;
				Page<ManageMsg> page = new Page<ManageMsg>(pageNoNew, total,list, pageSize);
				return page;
			}
		});
	}
	//tzf 首页模糊查询根据标题
	public Page<ManageMsg> findManageMsgByContent(int pageNo,int pageSize,int typeid,String likeName)
	{
		List<Criterion> condition = new ArrayList<Criterion>();
		if(typeid!=0){
			   condition.add(Restrictions.eq("bisType.id", typeid));
			}
		if(null != likeName && !likeName.trim().equals("")){
		   condition.add(Restrictions.like("title", likeName, MatchMode.ANYWHERE));
		}
		Page<ManageMsg> page = this.findPage(pageNo, pageSize, condition, Order.desc("addTime"));
		return page;
	}

	public List<ManageMsg> findMaybeSendMsgs() {
		List<Criterion> condition = new ArrayList<Criterion>();
		condition.add(Restrictions.eq("maybeSend", 1));
		Page<ManageMsg> page = this.findPage(1, 10000, condition, Order.desc("addTime"));
		return page.getData();
	}
	
}

